<template>
  <div class="list-container">
    <div class="bg-linear"
      id="linear">
      <div class="max-w-11xl mx-auto px-4 lg:flex lg:items-center py-5">
        <div class="lg:flex-1">
          <div class="text-base text-gray-1500 mb-3">
            {{$t('list_aiRankingByToolify')}}
          </div>
          <h1 class="text-40 text-gray-1000 break-words font-semibold"
            v-html="$t('list_aiRankingByToolifyRevenue')"></h1>
          <p class="text-base text-gray-1000 mt-3">
            {{$t('list_theListIsBasedOn_revenue')}}
          </p>
          <sponsored-by class="mt-4 text-lg text-gray-1000 font-semibold"></sponsored-by>
        </div>
        <div class="flex flex-wrap mt-4 gap-x-3 gap-y-4 lg:block lg:mt-0 lg:flex-shrink-0 lg:ml-3">
          <div class="flex items-center flex-wrap max-w-full gap-x-3 gap-y-4">
            <min-share class="min-share"></min-share>

            <el-popover placement="top"
              :trigger="_isMobile() ? 'click':'hover'">
              <div class="popover-box">
                <download-options @toDownload="toDownload"
                  :dStatus="dStatus"></download-options>
              </div>
              <div class="inline-flex items-center justify-center bg-purple-1300 px-3 py-3 group rounded-md hover:opacity-90 cursor-pointer"
                slot="reference">
                <svg-icon className="text-lg text-white"
                  :isDiv="true"
                  iconName='toolify_download'></svg-icon>
                <span class="text-sm text-white ml-2">{{$t('region_freeDownload')}}</span>
              </div>
            </el-popover>
          </div>
          <div class="flex justify-end flex-wrap max-w-full lg:mt-4">
            <a href="https://twitter.com/intent/user?&region=follow&screen_name=samChan3890089"
              rel="nofollow"
              target="_blank"
              class="flex-shrink-0 flex items-center justify-center bg-white px-3 h-11 group rounded-md hover:border hover:border-purple-1300 cursor-pointer">
              <svg-icon className="text-lg"
                :isDiv="true"
                iconName='twitter_logo'></svg-icon>
              <span class="text-sm text-gray-1000 ml-2 group-hover:text-purple-1300">{{$t('region_followUsToolify')}}</span>
            </a>
          </div>
        </div>
      </div>
    </div>

    <div class="max-w-11xl mx-auto px-4 py-6">
      <rank-list-tabs></rank-list-tabs>
      <div class="mt-3">
        <div class="bg-white rounded-md pt-5 px-5 pb-5">
          <div class="tTable"
            style="overflow-x: auto;"
            v-if="tableData && tableData.length>0">
            <table style="width: 100%; min-width: 780px;"
              class="fixTable">
              <thead id="thead">
                <tr>
                  <th style="width: 10%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_Ranking')}}
                    </div>
                  </th>
                  <th style="width: 18%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_Tools')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_url')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_snapshot')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_paymentPlatform')}}
                    </div>
                  </th>
                  <th style="width: 13%">
                    <div class="cell text-sm">
                      {{ $t('list_table_th_monthVisits') }}
                    </div>
                  </th>
                  <th style="width: 14%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_websiteDesc')}}
                    </div>
                  </th>
                </tr>
              </thead>
            </table>
            <table style="width: 100%; min-width: 780px;"
              class="commonTable">
              <thead id="thead">
                <tr>
                  <th style="width: 10%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_Ranking')}}
                    </div>
                  </th>
                  <th style="width: 18%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_Tools')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_url')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_snapshot')}}
                    </div>
                  </th>
                  <th style="width: 15%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_paymentPlatform')}}
                    </div>
                  </th>
                  <th style="width: 13%">
                    <div class="cell text-sm">
                      {{ $t('list_table_th_monthVisits') }}
                    </div>
                  </th>
                  <th style="width: 14%">
                    <div class="cell text-sm">
                      {{$t('list_table_th_websiteDesc')}}
                    </div>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr class="el-table__row"
                  v-for="(row, key) in tableData"
                  :key="key">
                  <td rowspan="1"
                    colspan="1"
                    class="el-table_1_column_1   el-table__cell">
                    <div class="cell">
                      <svg-icon v-if="key<3"
                        className="text-3xl mx-auto no-color"
                        :iconName='`no${key+1}`'></svg-icon>
                      <div v-else
                        class="text-center">
                        {{ key+1 }}
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <common-link path="/tool/:handle"
                        @click.native="handleExp(key, row)"
                        :params="{ handle:row.handle }"
                        :data-handle="row.handle"
                        :data-advertisement_id="row.advertisement_id ? row.advertisement_id : ''"
                        data-position="Revenue Rank"
                        :data-index="key"
                        class="text-base text-gray-1000 font-semibold hover:text-purple-1300 go-tool tool-dom"
                        target="_blank">
                        {{$websiteName(row)}}
                      </common-link>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <a :href="row.affiliate_link ? row.affiliate_link : row.website"
                        @click="handleExpWebsite(key, row)"
                        rel="nofollow"
                        target="_blank"
                        class="inline-block max-w-full line-3 text-sm text-gray-1000 hover:text-purple-1300 go-website break-words">
                        {{row.website}}
                      </a>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <div class="flex items-start justify-center rounded-lg overflow-hidden rank-tool-pic">
                        <common-image class="sm:h-49 w-full"
                          :src="row.image ? $vResetPic(row.image, 320) : 'https://cdn.toolify.ai/default.webp'"
                          :alt="$websiteName(row)"></common-image>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <p>
                        <span class="text-base text-gray-1000 capitalize"
                          v-if="Array.isArray(row.payment_platform)">
                          {{ row.payment_platform.join(', ') }}
                        </span>
                      </p>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <p>
                        <span class="text-base text-gray-1000"
                          v-if="hasRealVal(row.month_visited_count)">
                          {{ row.month_visited_count | vResetVisit }}
                        </span>
                      </p>
                    </div>
                  </td>
                  <td>
                    <div class="cell">
                      <p class="text-sm text-gray-1000 break-words tool-desc leading-7"
                        :title="row.description">
                        {{row.description}}
                      </p>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="w-2/4 mx-auto mt-6 text-center"
            v-if="tableData && tableData.length>0">
            <el-button type="text"
              v-if="tableData && tableData.length>0 && next_page_url"
              class="cursor-default">
              <img src="@/static/images/loading.png"
                class="loading"
                alt=""
                srcset="">
            </el-button>

            <el-divider v-else
              class="mt-12">
              <el-button type="text"
                class="cursor-default"
                :loading="loading">{{ $t('list_end') }}</el-button>
            </el-divider>
          </div>
          <el-empty v-if="(!tableData || tableData.length===0) && !loading"
            :description="$t('list_noData')"></el-empty>
        </div>
      </div>
    </div>

    <download-dom :title="$t('list_bestTrendingAITools')"
      :list="downloadList"
      :downloadType="downloadType"
      :pageDataNum="10"
      :toolCount="toolCount"
      :tableType="5"
      ref="download"
      @downloadStatus="downloadStatus">
      <div class="flex items-center"
        slot="data">
      </div>
    </download-dom>
  </div>
</template>

<script>
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapActions, mapState, mapMutations } from 'vuex'
export default {
  name: 'BestAIToolsSource',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error }) {
    try {
      let req = JSON.parse(
        JSON.stringify({
          page: 1,
          per_page: 50,
        })
      )

      let toolsRes = await $axiosApi.getHighRevenue({
        ...req,
      })

      let description = app.i18n.t('list_highRevenue_page_desc'),
        title = app.i18n.t('list_highRevenue_page_title')

      let res = {},
        toolCount = 0
      if (toolsRes.code === 200) {
        res.tableData =
          toolsRes.data.data && toolsRes.data.data.length > 0
            ? toolsRes.data.data
            : []

        res.page = toolsRes.data.current_page ? toolsRes.data.current_page : 1
        res.per_page = toolsRes.data.per_page ? toolsRes.data.per_page : 50
        res.next_page_url = toolsRes.data.next_page_url
          ? toolsRes.data.next_page_url
          : null
        res.total = toolsRes.data.total
        toolCount = toolsRes.data.tool_count
      } else {
        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: toolsRes.code,
          })
        }
      }

      return {
        ...res,
        title,
        description,
        toolCount,
      }
    } catch (err) {
      console.log(err)
    }
  },
  filters: {
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  mixins: [mixinsExposure],
  data() {
    return {
      uri: `https://www.toolify.ai${this.$route.fullPath}`,
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      tableData: [],
      page: 1,
      per_page: 50,

      next_page_url: null,
      errorImage: require('@/static/images/default.webp'),
      loading: false,
      total: 0,

      downloadList: [],
      downloadType: 'pdf',
      dStatus: null,

      toolCount: 0,
    }
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)
    window.addEventListener('resize', this.thFixed)
    this.thFixed()
  },
  methods: {
    ...mapActions(['exposure']),
    ...mapMutations(['SET_RetrackExposure']),
    onSroll() {
      this.thFixed()

      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight

      const footerHeight = document.querySelector('footer').offsetHeight
      //滚动条到底部的条件
      if (scrollTop + windowHeight + 1200 > scrollHeight - footerHeight) {
        if (this.next_page_url && !this.loading) {
          this.getList(this.page + 1)
        }
      }
    },
    thFixed() {
      if (
        !document.querySelector('.commonTable') ||
        !document.querySelector('.fixTable')
      ) {
        return false
      }
      const commonTable = document.querySelector('.commonTable')
      const fixTable = document.querySelector('.fixTable')

      const tableWidth = commonTable.offsetWidth
      const tableHeight = commonTable.offsetHeight
      const fixTableHeight = fixTable.offsetHeight
      const tableTop = commonTable.getBoundingClientRect().top
      const tableOffsetTop = commonTable.offsetTop
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      if (
        tableWidth > 780 &&
        tableTop <= 72 &&
        scrollTop < tableOffsetTop + tableHeight - fixTableHeight - 72
      ) {
        const distanceToLeft = commonTable.getBoundingClientRect().left
        const distanceToRight =
          window.innerWidth - commonTable.getBoundingClientRect().right

        fixTable.style.width = `${tableWidth}px`
        fixTable.style.zIndex = 10
        fixTable.style.left = `${distanceToLeft}px`
        fixTable.style.right = `${distanceToRight}px`
        fixTable.style.opacity = 1
      } else {
        fixTable.style.zIndex = -999
        fixTable.style.opacity = 0
      }
    },
    async getList(page) {
      this.loading = true
      try {
        let req = JSON.parse(
          JSON.stringify({
            page: page,
            per_page: 50,
          })
        )

        const res = await this.$axiosApi.getHighRevenue({
          ...req,
        })

        this.loading = false
        if (res.code === 200) {
          if (page === 1) {
            this.tableData = res.data.data
          } else {
            this.tableData = this.tableData.concat(res.data.data)
          }

          this.page = res.data.current_page ? res.data.current_page : 1
          this.per_page = res.data.per_page ? res.data.per_page : 50
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null
          this.total = res.data.total
          this.SET_RetrackExposure(Date.now())
        } else {
          //this.$message.error(res.message)
        }
      } catch (error) {
        this.loading = false
      }
    },

    toDownload(type) {
      this.dStatus = type
      this.downloadType = type

      let dataArr = this.tableData.slice(0, 50)
      this.downloadList = JSON.parse(JSON.stringify(dataArr))

      this.$nextTick(function () {
        if (this.$refs.download) {
          if (type === 'pdf') {
            this.$refs.download.getPdf()
          } else {
            this.$refs.download.getPic()
          }
        }
      })
    },
    downloadStatus(status) {
      this.dStatus = status
    },
    _isMobile() {
      if (process.browser) {
        let flag = navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        )
        return flag
      } else {
        return false
      }
    },

    handleExpWebsite(key = 0, toolsData) {
      this.getThrottledClickFunction(toolsData, key, true)()
    },
    handleExp(key = 0, toolsData) {
      this.getThrottledClickFunction(toolsData, key)()
    },
    getThrottledClickFunction(toolsData, key, isWebsite = false) {
      let functionKey = `${toolsData.handle}-${key}-website`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exportPreParams = {}
          if (isWebsite) {
            exportPreParams['target_url'] = toolsData.affiliate_link
              ? toolsData.affiliate_link
              : toolsData.website
          }
          let exporeData = this.getExporeData(
            toolsData,
            'Revenue Rank',
            key,
            false,
            exportPreParams
          )
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
    window.removeEventListener('resize', this.thFixed, false)
  },
}
</script>
<style lang='scss' scoped>
.list-container {
  background-color: #fafafa;
  ::v-deep .el-loading-mask {
    svg {
      margin-left: auto;
      margin-right: auto;
    }
  }
  ::v-deep .el-loading-mask {
    svg {
      margin-left: auto;
      margin-right: auto;
    }
  }
  .sourceActived {
    position: relative;
    &::after {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      height: 3px;
      content: '';
      background: #7150e6;
      border-radius: 2px;
    }
  }
  .tTable {
    background: #ffffff;
    border: 1px solid #e5e5e5;
    border-radius: 6px;

    table {
      table-layout: fixed;
      td,
      th {
        box-sizing: border-box;
        min-width: 0;
        padding: 12px 0;
        position: relative;
        text-align: left;
        text-overflow: ellipsis;
        vertical-align: middle;
        .cell {
          box-sizing: border-box;
          display: inline-block;
          padding-left: 10px;
          padding-right: 10px;
          position: relative;
          vertical-align: middle;
          width: 100%;
          text-overflow: ellipsis;
          line-height: 23px;
          overflow: hidden;
        }
        &:first-child {
          .cell {
            padding-left: 14px;
            text-align: center;
          }
        }
        &:last-child {
          .cell {
            padding-right: 14px;
          }
        }
      }
      &.fixTable {
        position: fixed;
        top: 72px;
        z-index: 10;
      }
      thead {
        tr {
          th {
            background: #f8f9fb;
            color: #666;
            font-weight: 400;
            border-bottom: 1px solid #ebeef5;
            .sortBox {
              display: flex;
              align-items: center;
              .sort {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                margin-left: 4px;
                .asc,
                .desc {
                  width: 8px;
                  height: 8px;
                  cursor: pointer;
                  svg {
                    font-size: 8px;
                    fill: #999;
                  }
                  &.actived {
                    svg {
                      fill: #7150e6;
                    }
                  }
                }
                .desc {
                  margin-top: 1px;
                }
              }
            }
          }
        }
      }
      tbody {
        tr {
          td {
            border-bottom: 1px solid #e5e5e5;
            color: #191919;
            font-size: 16px;
            padding-bottom: 16px;
            padding-top: 16px;
            transition: background-color 0.25s ease;
            .no-color {
              color: rgba(0, 0, 0, 0);
            }
            .no-color {
              color: rgba(0, 0, 0, 0);
            }

            .rank-tool-pic {
              width: 100%;
              max-width: 160px;
              max-height: 84px;
              border-radius: 10px 10px 0px 0px;
              overflow: hidden;
              img {
                border-radius: 10px 10px 0 0;
              }
            }
          }
          &:hover {
            td {
              background-color: #f5f7fa;
            }
          }

          &:last-child {
            td {
              border-bottom: 0;
            }
          }
        }
      }
    }
  }
}
</style>
